package com.xmy.cultivate.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmy.cultivate.constants.CommonConstant;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.entity.request.CisPositionRequest;
import com.xmy.cultivate.entity.views.GradePositionRequest;
import com.xmy.cultivate.service.*;
import com.xmy.cultivate.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 排班顺位表 前端控制器
 * </p>
 *
 * @author hpiggy
 * @since 2024-08-16
 */
@RestController
@RequestMapping("/api/cisPosition")
@Scope("prototype")
public class CisPositionController extends BaseController {

    @Autowired
    IdWorker idWorker;

    @Autowired
    ICisPositionService iCisPositionService;

    @Autowired
    ICisPositionDetailService iCisPositionDetailService;

    @Autowired
    IOrderApplyService iOrderApplyService;

    @Autowired
    IStudentClassTypeService iStudentClassTypeService;

    @Autowired
    ITranscriptService iTranscriptService;

    @Autowired
    IEnrollInfoService iEnrollInfoService;

    @Autowired
    ICourseTypeService iCourseTypeService;

    @Autowired
    IGradeService iGradeService;

    @Autowired
    ICourseSchedulingDetailService iCourseSchedulingDetailService;

    @Autowired
    IQuarterService iQuarterService;

    @GetMapping()
    public Result getCisPositionList(@RequestParam Map<String, String> reMap){
        int pageNum = StringUtils.isBlank(reMap.get("pageNum")) ? 1 : Integer.parseInt(reMap.get("pageNum"));
        int pageSize = StringUtils.isBlank(reMap.get("pageSize")) ? 10: Integer.parseInt(reMap.get("pageSize"));
        IPage<CisPosition> iPage = new Page<>(pageNum,pageSize);
        String teacherName = reMap.get("teacherName");
        String schoolName = reMap.get("schoolName");
        String teacherId = reMap.get("teacherId");
        String schoolId = reMap.get("schoolId");
        String yearPart = reMap.get("yearPart");
        String quarterNum = reMap.get("quarterNum");
        String subjectsId = reMap.get("subjectsId");
        String yearClassId = reMap.get("yearClassId");
        String classTypeId = reMap.get("classTypeId");
        String positionNum = reMap.get("positionNum");
        String peopleNum = reMap.get("peopleNum");
        QueryWrapper<CisPosition> cisPositionQueryWrapper = new QueryWrapper<>();
        cisPositionQueryWrapper.select("*,(SELECT name FROM staff WHERE id = cis_position.teacher_id LIMIT 1) AS teacherName,getSchoolName(school_id) AS schoolName");
        cisPositionQueryWrapper.eq("deleted",0);
        cisPositionQueryWrapper.eq(StringUtils.isNotBlank(teacherId), "teacher_id",teacherId);
        cisPositionQueryWrapper.eq(StringUtils.isNotBlank(schoolId), "school_id",schoolId);
        cisPositionQueryWrapper.eq(StringUtils.isNotBlank(yearPart), "year_part",yearPart);
        cisPositionQueryWrapper.eq(StringUtils.isNotBlank(quarterNum), "quarter_num",quarterNum);
        cisPositionQueryWrapper.eq(StringUtils.isNotBlank(subjectsId), "subjects_id",subjectsId);
        cisPositionQueryWrapper.inSql(StringUtils.isNotBlank(schoolName), "school_id","SELECT id FROM organization WHERE name LIKE '%"+schoolName+"%' AND deleted = 0");
        cisPositionQueryWrapper.inSql(StringUtils.isNotBlank(teacherName), "teacher_id","SELECT id FROM staff WHERE name LIKE '%"+teacherName+"%' AND deleted = 0");
        if (StringUtils.isNotBlank(yearClassId) || StringUtils.isNotBlank(classTypeId) || StringUtils.isNotBlank(positionNum) || StringUtils.isNotBlank(peopleNum)) {
            String sql = "";
            if (StringUtils.isNotBlank(yearClassId)) {
                sql += " AND year_class_id = " + yearClassId;
            }
            if (StringUtils.isNotBlank(classTypeId)) {
                sql += " AND class_type_id = " + classTypeId;
            }
            if (StringUtils.isNotBlank(positionNum)) {
                sql += " AND position_num = " + positionNum;
            }
            if (StringUtils.isNotBlank(peopleNum)) {
                sql += " AND people_num = " + peopleNum;
            }
            cisPositionQueryWrapper.inSql("id", "SELECT position_id FROM cis_position_detail WHERE deleted = 0 " + sql);
        }
        iCisPositionService.page(iPage, cisPositionQueryWrapper);
        if (iPage.getSize() > 0) {
            for (CisPosition cisPosition : iPage.getRecords()) {
                List<CisPositionDetail> positionDetails = iCisPositionDetailService.list(
                        new QueryWrapper<CisPositionDetail>()
                                .select("*,(SELECT name FROM course_type WHERE id = cis_position_detail.class_type_id) AS classTypeName")
                                .eq("position_id", cisPosition.getId())
                                .eq("deleted", 0)
                );
                cisPosition.setCisPositionDetailList(positionDetails);
                if (!positionDetails.isEmpty()) {
                    HashSet<Integer> yearClassIdHash = new HashSet<>();
                    for (CisPositionDetail cisPositionDetail : positionDetails) {
                        yearClassIdHash.add(cisPositionDetail.getYearClassId());
                    }
                    if (!yearClassIdHash.isEmpty()) {
                        StringBuilder yearClassIdStrBuilder = new StringBuilder();
                        for (Integer id : yearClassIdHash) {
//                            String yearClassForNum = ConfigData.getYearClassForNum(id);
                            if (yearClassIdStrBuilder.length() > 0) {
                                yearClassIdStrBuilder.append(",");
                            }
                            yearClassIdStrBuilder.append(id);
                        }
                        cisPosition.setYearClassIdSrc(yearClassIdStrBuilder.toString());
                    }
                }
            }
        }
        return new Result(Code.OK,new PageResult<>(iPage.getRecords(),iPage.getTotal(),iPage.getPages()));
    }

    @PostMapping()
    @Transactional
    public Result saveCisPosition(@RequestBody CisPositionRequest cisPositionRequest){
        CisPosition cisPosition = cisPositionRequest.getCisPosition();
        List<CisPositionDetail> cisPositionDetailList = cisPositionRequest.getCisPositionDetailList();
        Long id = idWorker.nextId();
        if (cisPosition.getLessonType() == null) {
            cisPosition.setLessonType(1);
        }
        CisPosition cisPositionServiceOne = iCisPositionService.getOne(
                new QueryWrapper<CisPosition>()
                        .eq("year_part", cisPosition.getYearPart())
                        .eq("quarter_num", cisPosition.getQuarterNum())
                        .eq("school_id", cisPosition.getSchoolId())
                        .eq("subjects_id", cisPosition.getSubjectsId())
                        .eq("teacher_id", cisPosition.getTeacherId())
                        .eq("lesson_type", cisPosition.getLessonType())
                        .eq("deleted", 0)
                        .last("limit 1")
        );
        if (cisPositionServiceOne != null) {
            id = cisPositionServiceOne.getId();
        }
        int isSave = 0;
        ArrayList<CisPosition> cisPositionArrayList = new ArrayList<>();
        StringBuilder msg = new StringBuilder();
        List<CisPositionDetail> cisPositionDetailArrayListAdd = new ArrayList<>();
        for (CisPositionDetail cisPositionDetail : cisPositionDetailList) {
            long isSaveYesOrNo = iCisPositionService.getIsSaveYesOrNo(cisPosition, cisPositionDetail);
            long count = getCount(cisPosition, cisPositionDetail);
            if (isSaveYesOrNo == 0 && count == 0) {
                isSave = 1;
                cisPositionDetail.setPositionId(id);
//                iCisPositionDetailService.save(cisPositionDetail);
                cisPositionDetailArrayListAdd.add(cisPositionDetail);
            } else {
                CisPosition one = iCisPositionService.getOne(
                        new QueryWrapper<CisPosition>()
                                .select("*,(SELECT name FROM staff WHERE id = cis_position.teacher_id LIMIT 1) AS teacherName,getSchoolName(school_id) AS schoolName," +
                                        "(SELECT name FROM course_type WHERE id = "+cisPositionDetail.getClassTypeId()+") AS classTypeIdStrBuilder")
                                .inSql("id", "SELECT t1.id FROM cis_position AS t1 " +
                                        "INNER JOIN cis_position_detail AS t2 ON t2.position_id = t1.id and t2.deleted = 0 " +
                                                " where " +
                                " t1.deleted = 0 " +
                                " and t1.year_part=" + cisPosition.getYearPart() +
                                " and t1.quarter_num=" + cisPosition.getQuarterNum() +
                                        " and t1.school_id=" + cisPosition.getSchoolId() +
                                        " and t1.subjects_id=" + cisPosition.getSubjectsId() +
                                        " and t2.year_class_id=" +  cisPositionDetail.getYearClassId() +
                                        " and t2.class_type_id=" +  cisPositionDetail.getClassTypeId() +
                                        " and t2.position_num=" +  cisPositionDetail.getPositionNum())
                                .last("limit 1")
                );
                if (one != null) {
                    one.setCisPositionDetail(cisPositionDetail);
                    cisPositionArrayList.add(one);
                    if (msg.length() > 0) {
                        msg.append(",");
                    }
                    String yearClassForNum = ConfigData.getYearClassForNum(cisPositionDetail.getYearClassId());
                    msg.append(one.getTeacherName()).append(" ").append(yearClassForNum).append(" ").append(one.getClassTypeIdStrBuilder()).append(" 第").append(cisPositionDetail.getPositionNum()).append("位");
                }
            }
        }
        if (isSave == 1 && cisPositionArrayList.isEmpty()) {
            iCisPositionDetailService.saveBatch(cisPositionDetailArrayListAdd);
            cisPosition.setId(id);
            cisPosition.setCreatedId(this.adminId);
            boolean save = iCisPositionService.saveOrUpdate(cisPosition);
            if (save) {
                return new Result(Code.OK,null,"添加成功");
            }
        }
        return new Result(Code.ERROR,cisPositionArrayList,"添加失败，已被：" + msg + "添加过！");
    }

    private long getCount(CisPosition cisPosition, CisPositionDetail cisPositionDetail) {
        return iCisPositionService.count(
                new QueryWrapper<CisPosition>()
                        .inSql("id", "SELECT t1.id FROM cis_position AS t1 " +
                                "INNER JOIN cis_position_detail AS t2 ON t2.position_id = t1.id and t2.deleted = 0 " +
                                " where " +
                                " t1.deleted = 0 " +
                                " and t1.teacher_id=" + cisPosition.getTeacherId() +
                                " and t1.year_part=" + cisPosition.getYearPart() +
                                " and t1.quarter_num=" + cisPosition.getQuarterNum() +
                                " and t1.school_id=" + cisPosition.getSchoolId() +
                                " and t1.subjects_id=" + cisPosition.getSubjectsId() +
                                " and t2.year_class_id=" +  cisPositionDetail.getYearClassId() +
                                " and t2.class_type_id=" +  cisPositionDetail.getClassTypeId()
                        )
        );
    }
    private long getCountYesId(CisPosition cisPosition, CisPositionDetail cisPositionDetail) {
        return iCisPositionService.count(
                new QueryWrapper<CisPosition>()
                        .inSql("id", "SELECT t1.id FROM cis_position AS t1 " +
                                "INNER JOIN cis_position_detail AS t2 ON t2.position_id = t1.id and t2.deleted = 0 " +
                                " where " +
                                " t1.deleted = 0 " +
                                " and t2.id <> " + cisPositionDetail.getId() +
                                " and t1.teacher_id=" + cisPosition.getTeacherId() +
                                " and t1.year_part=" + cisPosition.getYearPart() +
                                " and t1.quarter_num=" + cisPosition.getQuarterNum() +
                                " and t1.school_id=" + cisPosition.getSchoolId() +
                                " and t1.subjects_id=" + cisPosition.getSubjectsId() +
                                " and t2.year_class_id=" +  cisPositionDetail.getYearClassId() +
                                " and t2.class_type_id=" +  cisPositionDetail.getClassTypeId()
                        )
        );
    }
    @PutMapping()
    @Transactional
    public Result editCisPosition(@RequestBody CisPositionRequest cisPositionRequest){
        CisPosition cisPosition = cisPositionRequest.getCisPosition();
        List<CisPositionDetail> cisPositionDetailList = cisPositionRequest.getCisPositionDetailList();
        Long id = cisPosition.getId();
        if (id == null) {
            return new Result(Code.ERROR,null,"不存在");
        }
        CisPosition byId = iCisPositionService.getById(id);
        if (byId == null || byId.getDeleted() == null || byId.getDeleted() == 1) {
            return new Result(Code.ERROR,null,"不存在");
        }
        //先判断有没有不可以修改的
        int isSave = 0;
        ArrayList<CisPositionDetail> detailIdArrError = new ArrayList<>();
        StringBuilder msg = new StringBuilder();
        for (CisPositionDetail cisPositionDetail : cisPositionDetailList) {
            long isEditYesOrNo;
            long isCountTeacherId;
            if (cisPositionDetail.getId() != null) {
                isEditYesOrNo = iCisPositionService.getIsEditYesOrNo(cisPosition, cisPositionDetail);
                isCountTeacherId = getCountYesId(cisPosition, cisPositionDetail);
            } else {
                isEditYesOrNo = iCisPositionService.getIsSaveYesOrNo(cisPosition, cisPositionDetail);
                isCountTeacherId = getCount(cisPosition, cisPositionDetail);
            }
            if (isEditYesOrNo != 0 || isCountTeacherId != 0) {
                isSave = 1;
                detailIdArrError.add(cisPositionDetail);
                CisPosition one = iCisPositionService.getOne(
                        new QueryWrapper<CisPosition>()
                                .select("*,(SELECT name FROM staff WHERE id = cis_position.teacher_id LIMIT 1) AS teacherName,getSchoolName(school_id) AS schoolName," +
                                        "(SELECT name FROM course_type WHERE id = "+cisPositionDetail.getClassTypeId()+") AS classTypeIdStrBuilder")
                                .inSql("id", "SELECT t1.id FROM cis_position AS t1 " +
                                        "INNER JOIN cis_position_detail AS t2 ON t2.position_id = t1.id and t2.deleted = 0 " +
                                        " where " +
                                        " t1.deleted = 0 " +
                                        " and t1.year_part=" + cisPosition.getYearPart() +
                                        " and t1.quarter_num=" + cisPosition.getQuarterNum() +
                                        " and t1.school_id=" + cisPosition.getSchoolId() +
                                        " and t1.subjects_id=" + cisPosition.getSubjectsId() +
                                        " and t2.year_class_id=" +  cisPositionDetail.getYearClassId() +
                                        " and t2.class_type_id=" +  cisPositionDetail.getClassTypeId() +
                                        " and t2.position_num=" +  cisPositionDetail.getPositionNum())
                                .last("limit 1")
                );
                if (one != null) {
                    if (msg.length() > 0) {
                        msg.append(",");
                    }
                    String yearClassForNum = ConfigData.getYearClassForNum(cisPositionDetail.getYearClassId());
                    msg.append(one.getTeacherName()).append(" ").append(yearClassForNum).append(" ").append(one.getClassTypeIdStrBuilder()).append(" 第").append(cisPositionDetail.getPositionNum()).append("位");
                }
            }
        }
        if (isSave == 1) {
            return new Result(Code.ERROR, detailIdArrError, "修改失败，已被：" + msg + "添加过！");
        }
//        cisPosition = byId;//要可以修改的，所以这里不能重新给值
        ArrayList<Long> detailIdArr = new ArrayList<>();
        for (CisPositionDetail cisPositionDetail : cisPositionDetailList) {
            long isEditYesOrNo;
            if (cisPositionDetail.getId() != null) {
                isEditYesOrNo = iCisPositionService.getIsEditYesOrNo(cisPosition, cisPositionDetail);
            } else {
                isEditYesOrNo = iCisPositionService.getIsSaveYesOrNo(cisPosition, cisPositionDetail);
            }
            if (isEditYesOrNo == 0) {
                cisPositionDetail.setPositionId(id);
                iCisPositionDetailService.saveOrUpdate(cisPositionDetail);
            }
            detailIdArr.add(cisPositionDetail.getId());
        }
        if (!detailIdArr.isEmpty()) {
            iCisPositionDetailService.remove(new QueryWrapper<CisPositionDetail>().notIn("id", detailIdArr).eq("position_id" , id));
        }
        cisPosition.setDeleted(0);
        cisPosition.setCreatedId(byId.getCreatedId());
        iCisPositionService.updateById(cisPosition);
        return new Result(Code.OK,null,"修改成功");
    }

    @GetMapping("excel")
    public Result getCisPositionListExcel(@RequestParam Map<String, String> reMap){
        int pageNum = StringUtils.isBlank(reMap.get("pageNum")) ? 1 : Integer.parseInt(reMap.get("pageNum"));
        int pageSize = StringUtils.isBlank(reMap.get("pageSize")) ? 10: Integer.parseInt(reMap.get("pageSize"));
        IPage<CisPosition> iPage = new Page<>(pageNum,pageSize);
        String teacherName = reMap.get("teacherName");
        String schoolName = reMap.get("schoolName");
        String teacherId = reMap.get("teacherId");
        String schoolId = reMap.get("schoolId");
        String yearPart = reMap.get("yearPart");
        String quarterNum = reMap.get("quarterNum");
        String subjectsId = reMap.get("subjectsId");
        String yearClassId = reMap.get("yearClassId");
        String classTypeId = reMap.get("classTypeId");
        String positionNum = reMap.get("positionNum");
        String peopleNum = reMap.get("peopleNum");
        QueryWrapper<CisPosition> cisPositionQueryWrapper = new QueryWrapper<>();
        cisPositionQueryWrapper.select("*,(SELECT name FROM staff WHERE id = cis_position.teacher_id LIMIT 1) AS teacherName,getSchoolName(school_id) AS schoolName");
        cisPositionQueryWrapper.eq("deleted",0);
        cisPositionQueryWrapper.eq(StringUtils.isNotBlank(teacherId), "teacher_id",teacherId);
        cisPositionQueryWrapper.eq(StringUtils.isNotBlank(schoolId), "school_id",schoolId);
        cisPositionQueryWrapper.eq(StringUtils.isNotBlank(yearPart), "year_part",yearPart);
        cisPositionQueryWrapper.eq(StringUtils.isNotBlank(quarterNum), "quarter_num",quarterNum);
        cisPositionQueryWrapper.eq(StringUtils.isNotBlank(subjectsId), "subjects_id",subjectsId);
        cisPositionQueryWrapper.inSql(StringUtils.isNotBlank(schoolName), "school_id","SELECT id FROM organization WHERE name LIKE '%"+schoolName+"%' AND deleted = 0");
        cisPositionQueryWrapper.inSql(StringUtils.isNotBlank(teacherName), "teacher_id","SELECT id FROM staff WHERE name LIKE '%"+teacherName+"%' AND deleted = 0");
        if (StringUtils.isNotBlank(yearClassId) || StringUtils.isNotBlank(classTypeId) || StringUtils.isNotBlank(positionNum) || StringUtils.isNotBlank(peopleNum)) {
            String sql = "";
            if (StringUtils.isNotBlank(yearClassId)) {
                sql += " AND year_class_id = " + yearClassId;
            }
            if (StringUtils.isNotBlank(classTypeId)) {
                sql += " AND class_type_id = " + classTypeId;
            }
            if (StringUtils.isNotBlank(positionNum)) {
                sql += " AND position_num = " + positionNum;
            }
            if (StringUtils.isNotBlank(peopleNum)) {
                sql += " AND people_num = " + peopleNum;
            }
            cisPositionQueryWrapper.inSql("id", "SELECT position_id FROM cis_position_detail WHERE deleted = 0 " + sql);
        }
        iCisPositionService.page(iPage, cisPositionQueryWrapper);
        if (iPage.getSize() > 0) {
            for (CisPosition cisPosition : iPage.getRecords()) {
                List<CisPositionDetail> positionDetails = iCisPositionDetailService.list(
                        new QueryWrapper<CisPositionDetail>()
                                .select("*,(SELECT name FROM course_type WHERE id = cis_position_detail.class_type_id) AS classTypeName")
                                .eq("position_id", cisPosition.getId())
                                .eq("deleted", 0)
                );
                cisPosition.setCisPositionDetailList(positionDetails);
                if (!positionDetails.isEmpty()) {
                    HashSet<Integer> yearClassIdHash = new HashSet<>();
                    //唯一年级处理
                    for (CisPositionDetail cisPositionDetail : positionDetails) {
                        yearClassIdHash.add(cisPositionDetail.getYearClassId());
                    }
                    //年级id拼接
//                    if (!yearClassIdHash.isEmpty()) {
//                        StringBuilder yearClassIdStrBuilder = new StringBuilder();
//                        for (Integer id : yearClassIdHash) {
//                            if (yearClassIdStrBuilder.length() > 0) {
//                                yearClassIdStrBuilder.append(",");
//                            }
//                            yearClassIdStrBuilder.append(id);
//                        }
//                        cisPosition.setYearClassIdSrc(yearClassIdStrBuilder.toString());
//                    }
                    //班级拼接
                    HashMap<Integer, String> classTypeHash = new HashMap<>();
                    for (CisPositionDetail cisPositionDetail : positionDetails) {
                        Integer id = cisPositionDetail.getYearClassId();
                        String idHashStr = classTypeHash.get(id);
                        if (idHashStr == null) {
                            classTypeHash.put(id,cisPositionDetail.getClassTypeName() + "("+ cisPositionDetail.getPeopleNum() +") - 第"+cisPositionDetail.getPositionNum()+"位");
                        } else {
                            idHashStr = idHashStr + "    " + cisPositionDetail.getClassTypeName() + "("+ cisPositionDetail.getPeopleNum() +") - 第"+cisPositionDetail.getPositionNum()+"位";
                            classTypeHash.put(id,idHashStr);
                        }
                    }
                    //年级、班级写入实体字段
                    StringBuilder yearClassIdStrBuilder = new StringBuilder();
                    StringBuilder classTypeIdStrBuilder = new StringBuilder();
                    for (Integer id : yearClassIdHash) {
                        String yearClassForNum = ConfigData.getYearClassForNum(id);
                        if (yearClassIdStrBuilder.length() > 0) {
                            yearClassIdStrBuilder.append((char) 10);
                        }
                        yearClassIdStrBuilder.append(yearClassForNum);
                        if (classTypeIdStrBuilder.length() > 0) {
                            classTypeIdStrBuilder.append((char) 10);
                        }
                        classTypeIdStrBuilder.append(classTypeHash.get(id));
                    }
                    cisPosition.setYearClassIdStrBuilder(yearClassIdStrBuilder.toString());
                    cisPosition.setClassTypeIdStrBuilder(classTypeIdStrBuilder.toString());
                    String subjectsNameForNum = ConfigData.getSubjectsNameForNum(Math.toIntExact(cisPosition.getSubjectsId()));
                    cisPosition.setSubjectsName(subjectsNameForNum);
                }
            }
        }
        String fileName = "排班顺位";

        ExcelUtil.export(fileName, iPage.getRecords(), CisPosition.class, response);

        return new Result(Code.OK,null,"导出成功");
    }

    /**
     * 获取是否有顺位班级
     * @param subjectsId
     * @param studentId
     * @param yearClassId
     * @param schoolId
     * @return
     */
    @GetMapping("/getPositionGrade")
    public Result getPositionGrade(@RequestParam("subjectsId") Long subjectsId,
                                  @RequestParam("studentId") Long studentId,
                                  @RequestParam("yearClassId") Integer yearClassId,
                                  @RequestParam("schoolId") Long schoolId){
        Quarter quarterNow = iQuarterService.getNowQuarter();
        //获取上一个学期
        Quarter lastQuarter = iQuarterService.getLastQuarter(quarterNow.getYearPart(), quarterNow.getNum());
        if (lastQuarter.getType().equals(2)) {
            //如果上一学期为假期，再获取上一学期
            lastQuarter = iQuarterService.getLastQuarter(lastQuarter.getYearPart(), lastQuarter.getNum());
        }
        //StudentClassType studentClassType = iStudentClassTypeService.getAutoDivideClassType(quarterNow.getYearPart(),quarterNow.getNum(),subjectsId,studentId,yearClassId);
        GradePositionRequest gradePositionRequest = iStudentClassTypeService.getAutoDivideClassTypeOrScore(quarterNow.getYearPart(),quarterNow.getNum(),subjectsId,studentId,yearClassId);

        //if (studentClassType == null){
        //    //根据分数更新可分班型
        //    iEnrollInfoService.addDataTranscript(quarterNow,lastQuarter,studentId,subjectsId);
        //}

        //0为新生
        Long count = iOrderApplyService.getApplyCountForIsNew(subjectsId.toString(),studentId.toString());
        Integer hasPostion = 1;
        String msg = "";
        Map<String,Object> map = new HashMap<>();

        Company company = iCompanyService.getById(CommonConstant.companyId);
        if (company!=null){
            if (company.getStuIsHierarchy().equals(1)){
                //为0新生
                if (count.equals(0L)){
                    if (gradePositionRequest.getIsHasData().equals(0)) {
                        msg = lastQuarter.getYearPart()+lastQuarter.getName()+"期末成绩未填写，不能报名，请先去填写期末成绩";
                        hasPostion = 2;
                    }else {
                        List<Grade> positionGradeList = iGradeService.getPositionGradeList(quarterNow.getYearPart(),quarterNow.getNum(),schoolId,subjectsId,yearClassId,1,gradePositionRequest.getType(),gradePositionRequest.getScore(),gradePositionRequest.getClassTypeId());
                        Integer gradeCount = 0 ;
                        for (Grade grade:positionGradeList){
                            //查看是否有时间冲突
                            List<CourseSchedulingDetail> courseSchedulingDetailList = iCourseSchedulingDetailService.getSchedulingClashForDate(grade.getYearPart(),grade.getQuarterNum(),studentId,grade.getId(), LocalDateTime.now().withNano(0).toString());
                            if (courseSchedulingDetailList.size() == 0){
                                gradeCount++;
                            }
                        }

                        if (gradeCount ==0){
                            hasPostion = 0;
                            String classTypeName = "";
                            if (gradePositionRequest.getType().equals(2)) {
                                classTypeName = iCourseTypeService.getNameForId(gradePositionRequest.getClassTypeId());
                            }else {
                                classTypeName = "分数为："+gradePositionRequest.getScore();
                            }
                            msg = quarterNow.getYearPart()+quarterNow.getName()+CommonUtil.getYearClassNameForId(yearClassId)+","+CommonUtil.getSubjectsNameForId(Integer.parseInt(subjectsId.toString()))+","+classTypeName+"，没有可排班的班级";
                        }
                    }
                }
            }
        }

        map.put("type",hasPostion);
        map.put("msg",msg);
        //map.put("gradeList",gradeList);
        return new Result(Code.OK,map,"");
    }

}
